var ctx=window.daijia.ctx;

var offset=0;
var limit=20;
var pagingLimit=20;//显示分页时的条数
var currentTotalElements=0;//当前显示总条数


var pageLoading=true;//是否能滚动加载
var hasShowPages=false;//是否已显示分页
var firstLoadPages=true;//分页初始化时 不自动加载

//筛选条件
var search_name=null;


$(document).ready(function(){
	
	
	initdata(false);
	

	
	//查询
	$("#searchButton").click(function(){
		search_name=$("#name").val();
		offset=0;
		initdata(false);
		
	});
	
	$(document).on("keydown","body",function(){
		if(window.event.keyCode == 13){
			$("#searchButton").click();
		}
	});
	
	//滚动
//	$(window).scroll(function () {
//        //$(window).scrollTop()这个方法是当前滚动条滚动的距离
//        //$(window).height()获取当前窗体的高度
//        //$(document).height()获取当前文档的高度
//        var bot = 0; //bot是底部距离的高度
//        if ((bot + $(window).scrollTop()) >= ($(document).height() - $(window).height())) {
//           //当底部基本距离+滚动的高度〉=文档的高度-窗体的高度时；
//        	if(pageLoading){
//        		pageLoading=false;
//        		offset+=limit;
//        		initdata(true);
//        	}
//        }
//    });
	
});
//多选
var thisButton;
function deleteRecord() {
    $.post(ctx+'/driver/deleteRecord',{'id':thisButton.attr("data-value")},function(data){
            if(data.success){
                $.scojs_message('通话记录删除成功', $.scojs_message.TYPE_OK);
                window.location.reload(true);
            } else {
                $.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
            }
    },'json');
}
function deleteRecords() {
	var delete_ids=[]; 
	$("input[name=ids]:checked").each(function(index,element){
    	delete_ids.push($(element).val());
    });
    $.post(ctx+'/driver/deleteRecords',{'ids':delete_ids.toString()},function(data){
            if(data.success){
                $.scojs_message('通话记录删除成功', $.scojs_message.TYPE_OK);
                window.location.reload(true);
            } else {
                $.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
            }
    },'json');
}

$(document).ready(function(){
    $(".deletethis").click(function(){
          thisButton = $(this);
          var confirm = $.scojs_confirm({
            content: "你真的要删除该通话记录吗？",
            action:deleteRecord
          });
          confirm.show();
    });
    
    $("#checkAll").click(function(){
    	var thischeck=this.checked;
    	$("input[name=ids]").each(function(index,element){
    		element.checked=thischeck;
    	});
    });
    
    $("#delete_checked").click(function(){
    	if($("input[name=ids]:checked").length<=0){
    		$.scojs_message("请勾选需要删除的记录", $.scojs_message.TYPE_ERROR);
    		return false;
    	}
    	thisButton = $(this);
        var confirm = $.scojs_confirm({
	        content: "你真的要删除勾选的通话记录吗？",
	        action:deleteRecords
        });
        confirm.show();
    	
    	
    });
    
    
});

function initdata(isappend){
	
//	showLoading();
	$.ajax({
        url : ctx+'/driver/recordListData',
        type:'GET',
        async:false,
        dataType : 'json',
        data : {
        	"param":search_name,
        	"pager.offset":offset,
        	"limit":limit,
        },
        success : function(result){
        	var newcontent = '';
        	var totalElements=result.totalElements;
        	$("#NoData").text("");
			
        	if(totalElements>0){
        		
    			
        		$(result.content).each(function(index,data){
        			var statusColor="";
        			var mainButton="";
        			statusColor="btn-primary";
        			mainButton="<a href='javascript:;' data-value='"+data.id+"' class='btn btn-primary btn-xs deletethis'>删除</a>";
        			var allButton="<div class='btn-group'>"+
        			mainButton+
        			"</div>";
        			
        				
        			var currentCompany;
        			if(data.currentCompany){
        				currentCompany="<td>是</td>";
        			}else{
        				currentCompany="<td>否</td>";
        			}
        			var phoneTime;
        			if(data.phoneType==1){
        				if(data.phoneTime>0){
        					phoneTime = "<td>"+data.phoneTime+"(来电)</td>";
        				}else{
        					phoneTime = "<td>(服务人员挂断)</td>";
        				}
        			}else if(data.phoneType==2){
        				if(data.phoneTime>0){
        					phoneTime = "<td>"+data.phoneTime+"(去电)</td>";
        				}else{
        					phoneTime = "<td>(服务人员挂断)</td>";
        				}
        			}else if(data.phoneType==3){
        				phoneTime = "<td>(客户挂断/服务人员未接)</td>";
        			}
        			var hasOrders;
        			if(data.hasOrders){
        				hasOrders = "<td>有</td>";
        			}else{
        				hasOrders = "<td><font color='red'>没有</font></td>"
        			}
        			
        			
	    newcontent+="<tr class='grid-data tr-hui' style='display:none;'>"+
						"<td>"+"<input value='"+data.id+"' type='checkbox' name='ids'>"+"</td>"+
						"<td>"+allButton+"</td>"+
						"<td>"+data.driverName+"</td>"+
						"<td>"+data.driverPhone+"</td>"+
						"<td>"+data.memberPhone+"</td>"+
						"<td>"+data.memberName+"</td>"+
						"<td>"+(new Date(data.phoneDate).Format("yyyy-MM-dd hh:mm"))+"</td>"+
								currentCompany+
								phoneTime+
								hasOrders+
						"<td>"+allButton+"</td>"+
					"</tr>";
        		});
        		
        		
        	}
        	else{
             	 $("#NoData").text("当前页面暂无记录 ");
            }

//        	hideLoading();
        	
        	if(!isappend){
        		$(".table tbody .grid-data").remove();
        	}
        	$(".table tbody").append(newcontent);
        	
        	$(".table tbody .grid-data").each(function(index,element){
        		$(element).fadeIn(200+(index*35));
        	});
        	
        	
        	if(!hasShowPages){
        		if(!isappend){
            		currentTotalElements=result.content.length;
            		pageLoading=true;
            	}
        		else{
            		if(currentTotalElements<totalElements){
            			currentTotalElements+=result.content.length;
            			pageLoading=true;
            		}
            		else{
            			pageLoading=false;
            		}
            	}
        	}

        	if(hasShowPages){
    			firstLoadPages=true;
        		$(".pageshow li a").html("共"+totalElements+" 条数据");
        		$(".pagedata").paging(totalElements, {
        			format: '[< ncnnn >]',
        			perpage: pagingLimit,
        			page:(offset/limit)+1,
        			onSelect: function (page) {
        				limit=pagingLimit;
        				offset=(page-1)*limit;
        				if(!firstLoadPages){
        					initdata(false);
        				}
        				firstLoadPages=false;
        		    	return false;
        			},
        			onFormat: function (type) {
        				switch (type) {
        				case 'block': // n and c
        					if (!this.active)
        						return '';
        					else if (this.value != this.page)
        						return '<li><a href="#">' + this.value + '</a></li>';
        					return '<li class="active"><a href="#">' + this.value + '</a></li>';
        				case 'next': // >
        					return '<li><a href="#">&rsaquo;</a><li>';
        				case 'prev': // <
        						return '<li><a href="#">&lsaquo;</a><li>';
        				case 'first': // [
        						return '<li><a href="#">&laquo;</a><li>';
        				case 'last': // ]
        						return '<li><a href="#">&raquo;</a></li>';
        				}
        			}
        		});
        		
        	}
        	else{
        		//滚动达到pagingLimit条开始显示分页
//        		if(currentTotalElements==pagingLimit){
            		
            		pageLoading=false;
            		hasShowPages=true;
            		
            		$(".pageshow").show();
            		$(".pagedata").show();
            		$(".pageshow li a").html("共"+totalElements+" 条数据");
            		$(".pagedata").paging(totalElements, {
            			format: '[< ncnnn >]',
            			perpage: pagingLimit,
            			onSelect: function (page) {
            				limit=pagingLimit;
            				offset=(page-1)*limit;
            				if(!firstLoadPages){
            					initdata(false);
            				}
            				firstLoadPages=false;
            		    	return false;
            			},
            			onFormat: function (type) {
            				switch (type) {
            				case 'block': // n and c
            					if (!this.active)
            						return '';
            					else if (this.value != this.page)
            						return '<li><a href="#">' + this.value + '</a></li>';
            					return '<li class="active"><a href="#">' + this.value + '</a></li>';
            				case 'next': // >
            					return '<li><a href="#">&rsaquo;</a><li>';
            				case 'prev': // <
            						return '<li><a href="#">&lsaquo;</a><li>';
            				case 'first': // [
            						return '<li><a href="#">&laquo;</a><li>';
            				case 'last': // ]
            						return '<li><a href="#">&raquo;</a></li>';
            				}
            			}
            		});
            		
//            	}
        	}
        	
        }
	});
	
}

function showLoading(){
	if($('#loadblacklayer').length==0){
		var dw = $(".table").width();
		var dh = $(".table").height();
		var backlayer ="<div id='loadblacklayer'><div style='margin-top:"+(dh/2)+"px;margin-left:"+(dw/2)+"px;'><img src='"+ctx+"/assets/css/images/loading.gif' /></div></div>"
		$(".table tbody").append(backlayer);
		$('#loadblacklayer').css({"z-index":"9","background":"#000","opacity":"0.5","position":'absolute',"top":0,"width":dw,"height":dh});
	}
}

function hideLoading(){
	if($('#loadblacklayer').length>0){
		$('#loadblacklayer').remove();
	}
}
Date.prototype.Format = function(fmt) 
{ 
  var o = { 
    "M+" : this.getMonth()+1,                 //月份 
    "d+" : this.getDate(),                    //日 
    "h+" : this.getHours(),                   //小时 
    "m+" : this.getMinutes(),                 //分 
    "s+" : this.getSeconds(),                 //秒 
    "q+" : Math.floor((this.getMonth()+3)/3), //季度 
    "S"  : this.getMilliseconds()             //毫秒 
  }; 
  if(/(y+)/.test(fmt)) 
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
  for(var k in o) 
    if(new RegExp("("+ k +")").test(fmt)) 
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
  return fmt; 
}
